<?php
defined('IN_MAIN') or exit('Invalid Access!');

function calc_pool($in_date){
	global $vars;
	$db=$vars["db"];
	$pairing_volume_type = $vars['pairing_volume_type'];
	$pool = $vars['pool'];
	$pool_auto_qualifiers = $vars['pool_auto_qualifiers'];
	$min_maintain = $vars['min_maintain'];
	$maintenance_percent = $vars['maintenance_percent'];
	$max_maintain = $vars['max_maintain'];		$jp_max_maintain = $vars['jp_max_maintain'];
	
	$year = date("Y", strtotime($in_date));
	$month = date("n", strtotime($in_date));
	$calc_date['start']=date('Y-m-d H:i:s', mktime(0, 0, 0, $month, 1, $year));
	$calc_date['end']=date('Y-m-d H:i:s', mktime(23, 59, 59, $month+1, 0, $year));
	$last_month_time = mktime(0, 0, 0, $month-1, 1, $year);
	$last_month_year = date('Y', $last_month_time);
	$last_month_month = date('n', $last_month_time);
	$maintain_time=mktime(0, 0, 0, $month+1, 1, $year);
	$maintain_year = date("Y", $maintain_time);
	$maintain_month = date("n", $maintain_time);
	$total_pool = count($pool);
	
	$sales_his_safe = false;
	if(!mysql_query("truncate $db->purchase_calc")){
		$sales_his_safe = true;
	}else{
		$ins_total = 0;
		$t = @mysql_num_rows($r=mysql_query("select id, uid, total_bv from $db->purchase where status='confirmed' and member_sale='y' and first_sale='y' and no_bv!='y' and cdate>='$calc_date[start]' and cdate<='$calc_date[end]'"));
		for($i=0;$i<$t;$i++){
			$his = mysql_fetch_assoc($r);
			$ins .= "('$his[id]', '$his[uid]', '$his[total_bv]'),";
			$ins_total++;
			if($ins_total > 200){
				$ins = rtrim($ins, ',');
				$ins_sql = "insert into $db->purchase_calc (id, uid, total_bv) values $ins";
				if(!mysql_query($ins_sql)){
					$i = $t;
					$sales_his_safe = true;
				}
				$ins = '';
				$ins_total = 0;
			}
		}
		if($ins){
			$ins = rtrim($ins, ',');
			$ins_sql = "insert into $db->purchase_calc (id, uid, total_bv) values $ins";
			if(!mysql_query($ins_sql)){
				$sales_his_safe = true;
			}
		}
		unset($his, $ins, $ins_sql, $ins_total);
	}
	$carryforward_safe = false;
	if(!mysql_query("truncate $db->member_cf_calc")){
		$carryforward_safe = true;
	}else{
		$ins_total = 0;
		$t = @mysql_num_rows($r=mysql_query("select uid, amount from $db->member_cf where cdate='$last_day'"));
		for($i=0;$i<$t;$i++){
			$his = mysql_fetch_assoc($r);
			$ins .= "('$his[uid]', '$his[amount]'),";
			$ins_total++;
			if($ins_total > 200){
				$ins = rtrim($ins, ',');
				$ins_sql = "insert into $db->member_cf_calc (uid, amount) values $ins";
				if(!mysql_query($ins_sql)){
					$i = $t;
					$carryforward_safe = true;
				}
				$ins = '';
				$ins_total = 0;
			}
		}
		if($ins){
			$ins = rtrim($ins, ',');
			$ins_sql = "insert into $db->member_cf_calc (uid, amount) values $ins";
			if(!mysql_query($ins_sql)){
				$carryforward_safe = true;
			}
		}
		unset($his, $ins, $ins_sql, $ins_total);
	}
	
	$t=@mysql_num_rows($r=mysql_query("select * from $db->users where activated='y' order by id desc"));
	
	for($i=0;$i<$t;$i++){
		$member = mysql_fetch_assoc($r);
		
		$uid = $member['id'];
		$personal_volume = @mysql_result(mysql_query("select sum(total_bv) from $db->purchase where uid='$uid' and first_sale='y' and no_bv!='y' and status='confirmed' and cdate>='$calc_date[start]' and cdate<='$calc_date[end]'"), 0) or 0;
		
		$t2 = @mysql_num_rows($r2=mysql_query("select id, matrix_position from $db->users where matrix_upline='$uid'"));
		for($j=0;$j<$t2;$j++){
			$downline = mysql_fetch_assoc($r2);
			$did = $downline['id'];
			$position = $downline['matrix_position'];
			$all_did = $did;
			$uplines[0] = $did;
			$this_volume = 0;
			do{
				
				$t3 = @mysql_num_rows($r3=mysql_query("select id from $db->users where matrix_upline in (".implode(',', $uplines).")"));
				unset ($uplines);
				for($k=0;$k<$t3;$k++){
					$ddownlines = mysql_fetch_assoc($r3);
					$ddid = $ddownlines['id'];
					
					if($member_legss[$ddid]){
						foreach($member_legss[$ddid] as $details){
							$this_volume += $details['avolume'];
						}
					}else{
						$uplines[] = $ddid;
					}
					$all_did .= ','.$ddid;
				}
			}while ($uplines);
			
			
			if($sales_his_safe){
				$sql = "select sum(total_bv) from $db->purchase where first_sale='y' and no_bv!='y' and uid in ($all_did) and status='confirmed' and cdate>='$calc_date[start]' and cdate<='$calc_date[end]'";
			}else{
				$sql = "select sum(total_bv) from $db->purchase_calc where uid in ($all_did)";
			}
			$volume = @mysql_result(mysql_query($sql), 0) or 0;
			
			if($carryforward_safe){
				$sql = "select amount from $db->member_cf where uid='$did' and cdate='$last_day'";
			}else{
				$sql = "select amount from $db->member_cf_calc where uid='$did'";
			}
			$carryforward = @mysql_result(mysql_query($sql), 0) or 0;
			
			$total_bv = $volume + $this_volume + $carryforward;
			$total_abv = $volume + $this_volume;
			$downlines_id[$j] = $did;
			$downlines_bv[$j] = $total_bv;
			$downlines_dd[$did]['position'] = $position;
			$downlines_dd[$did]['volume'] = $total_bv;
			$downlines_dd[$did]['avolume'] = $total_abv;
		}
		if($downlines_id && $downlines_bv){
			array_multisort($downlines_bv, SORT_DESC, $downlines_id, SORT_ASC);
			for($j=0,$t2=count($downlines_id);$j<$t2;$j++){
				$legs[$j]["id"]=$downlines_id[$j];
				$legs[$j]['position'] = $downlines_dd[$downlines_id[$j]]['position'];
				$legs[$j]['volume']=$downlines_bv[$j];
				$legs[$j]['left_volume'] = $downlines_bv[$j];
				$legs[$j]['avolume'] = $downlines_dd[$downlines_id[$j]]['avolume'];
			}
		}
		$member_legs = $legs;
		$member_legss[$uid] = $legs;
		unset ($legs, $downlines_id, $downlines_bv, $uplines, $all_did);
		
		
		$group_volume = $personal_volume;
		if(count($member_legs)){
			foreach($member_legs as $detail){
				$group_volume += $detail['avolume'];
			}
		}
		
		for ($j=$total_pool;$j>0;$j--){
			
			if(is_array($pool_auto_qualifiers) && in_array($uid, $pool_auto_qualifiers)){
				for ($k=$j;$k>=1;$k--){
					
					$pool_qualifier[$k][] = $uid;
					$pool_share[$k] += 1;
				}
				
				$j=0;
			}else{
				if ($group_volume >= $pool[$j]['volume']){
					
					$min_leg = $pool[$j]['min_leg'];
					
					if(count($member_legs)){
						foreach ($member_legs as $details){
							
							if ($min_leg > 0){
								
								if ($details['avolume'] >= $pool[$j]['min_leg_volume']){
									
									$min_leg -= 1;
								}
							}
						}
					}
					
					if ($min_leg == 0){
						
						for ($k=$j;$k>=1;$k--){
							
							$pool_qualifier[$k][] = $uid;
							$pool_share[$k] += 1;
						}
						
						$j=0;
					}
				}
			}
		}
	}
	
	
	$cto = @mysql_result(mysql_query("select sum(total_bv) from $db->purchase where first_sale='y' and no_bv!='y' and status='confirmed' and cdate>='$calc_date[start]' and cdate<='$calc_date[end]'"), 0) or 0;
	
	for ($i=1;$i<=$total_pool;$i++){
		
		$poolbf = @mysql_result(mysql_query("select amount from $db->pool_cf where type='$i' and month='$last_month_month' and year='$last_month_year'"), 0) or 0;
		
		$pool_amount = round($cto * $pool[$i]['percent'] / 100, 2) + $poolbf;
		
		if (count($pool_qualifier[$i])){
			
			$comm_amount = round($pool_amount / $pool_share[$i], 2);
			
			for($j=0,$t2=count($pool_qualifier[$i]);$j<$t2;$j++){
				
				$uid = $pool_qualifier[$i][$j];
				
				$sql = "insert into $db->member_comm (uid, type, amount, percent, year, month, status, cdate) values ('$uid', '$i', '$comm_amount', '".$pool[$i]['percent']."', '$year', '$month', 'confirmed', '".ndate($vars['system_date_format'])."')";
				
				$insert_comm_detail="UID: $uid Amount: $comm_amount Percent: ".$pool[$i]['percent']."%<br />\n";
				if(!mysql_query($sql)){
					$insert_error[$i].=$insert_comm_detail."SQL: $sql<br />\n";
				}else{
					$insert_success[$i].=$insert_comm_detail;
				}
				
				$member_comm[$uid][$i] += $comm_amount;
			}
		}else{
			
			$sql = "insert into $db->pool_cf (type, amount, year, month) values ('$i', '$pool_amount', '$year', '$month')";
			
			if(!mysql_query($sql)){
				$insert_poolcf_error.="Pool $i: Amount: $pool_amount Percent: ".$pool[$i]['percent']."%<br />\n";
			}
		}
	}
	
	if ($member_comm){
		foreach ($member_comm as $uid => $details){
			foreach($details as $comm_code => $amount){
				$total_maintain_amount = $maintain_amount = round($amount * $maintenance_percent / 100, 2);
				$next_month_maintain = @mysql_result(mysql_query("select sum(amount) from $db->member_maintain where uid='$uid' and year='$maintain_year' and month='$maintain_month'"), 0) or 0;				$user_country = @mysql_result(mysql_query("select country from $db->users where id='$uid'"), 0) or 0;							if($user_country=='JP'){					if($next_month_maintain < $jp_max_maintain){						$maintain_amount = round($amount * $maintenance_percent / 100, 2);							if($maintain_amount + $next_month_maintain > $jp_max_maintain){								$maintain_amount = $jp_max_maintain - $next_month_maintain;							}													$sql = "insert into $db->member_maintain (uid, comm_type, percent, amount, year, month, cdate)							values ('$uid', '$comm_code', '$maintenance_percent', '$maintain_amount', '$maintain_year', '$maintain_month', '".ndate()."')";							if(!mysql_query($sql)){								$insert_main_err.="UID: $uid, comm code: $comm_code, percent: $maintenance_percent%, amount: $maintain_amount, year: $maintain_year, month: $maintain_month\n";							}						}else{							$maintain_amount = 0;						}				}else{					if($next_month_maintain < $max_maintain){						$maintain_amount = round($amount * $maintenance_percent / 100, 2);							if($maintain_amount + $next_month_maintain > $max_maintain){								$maintain_amount = $max_maintain - $next_month_maintain;							}													$sql = "insert into $db->member_maintain (uid, comm_type, percent, amount, year, month, cdate)							values ('$uid', '$comm_code', '$maintenance_percent', '$maintain_amount', '$maintain_year', '$maintain_month', '".ndate()."')";							if(!mysql_query($sql)){								$insert_main_err.="UID: $uid, comm code: $comm_code, percent: $maintenance_percent%, amount: $maintain_amount, year: $maintain_year, month: $maintain_month\n";							}						}else{							$maintain_amount = 0;						}				}
				
				
				$actual_amount = $amount - $total_maintain_amount;
				if(!mysql_query($sql="update $db->users set ewallet=ewallet+$actual_amount where id='$uid' limit 1")){
					$update_ew_err.="UID: $uid, amount: $actual_amount\n";
				}elseif(!mysql_query($sql="insert into $db->member_ewallet_record (uid, type, amount, descr, cdate) values ('$uid', 'credit', '$amount', '".addslashes("Credited $vars[currency]".number_format($amount, 2)." from Pool received.")."', '".ndate()."')")){
					$insert_ewrec_err.=$sql."\n";
				}else{
					$new_eid = mysql_insert_id();
					$last_bal = @mysql_result(mysql_query("select bal from $db->member_ewallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
					if(!$last_bal){
						$last_bal = 0;
					}
					$last_bal += $amount;
					@mysql_query("update $db->member_ewallet_record set bal='$last_bal' where id='$new_eid' limit 1");
				}
				
				if($maintain_amount > 0){
					
					if(!mysql_query($sql="insert into $db->member_ewallet_record (uid, type, amount, descr, cdate) values ('$uid', 'debit', '$maintain_amount', '".addslashes("Debited $vars[currency]".number_format($maintain_amount, 2)." for maintenance from Pool received.")."', '".ndate()."')")){
						$insert_ewrec_err.=$sql."\n";
					}else{
						$new_eid = mysql_insert_id();
						$last_bal = @mysql_result(mysql_query("select bal from $db->member_ewallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
						if(!$last_bal){
							$last_bal = 0;
						}
						$last_bal -= $maintain_amount;
						@mysql_query("update $db->member_ewallet_record set bal='$last_bal' where id='$new_eid' limit 1");
					}
					
					
					if(!mysql_query($sql="update $db->users set swallet=swallet+$maintain_amount where id='$uid' limit 1")){
						$update_sw_err.="UID: $uid, amount: $maintain_amount\n";
					}elseif(!mysql_query($sql="insert into $db->member_swallet_record (uid, type, amount, descr, cdate) values ('$uid', 'credit', '$maintain_amount', '".addslashes("Credited $vars[currency]".number_format($maintain_amount, 2)." for maintenance from Pool received.")."', '".ndate()."')")){
						$insert_swrec_err.=$sql."\n";
					}else{
						$new_eid = mysql_insert_id();
						$last_bal = @mysql_result(mysql_query("select bal from $db->member_swallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
						if(!$last_bal){
							$last_bal = 0;
						}
						$last_bal += $maintain_amount;
						@mysql_query("update $db->member_swallet_record set bal='$last_bal' where id='$new_eid' limit 1");
					}
				}
				
				$mall_point = $total_maintain_amount - $maintain_amount;
				if($mall_point > 0){
					
					if(!mysql_query($sql="insert into $db->member_ewallet_record (uid, type, amount, descr, cdate) values ('$uid', 'debit', '$mall_point', '".addslashes("Debited $vars[currency]".number_format($mall_point, 2)." for maintenance from bulk Pool commission received.")."', '".ndate()."')")){
						$insert_ewrec_err.=$sql."\n";
					}else{
						$new_eid = mysql_insert_id();
						$last_bal = @mysql_result(mysql_query("select bal from $db->member_ewallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
						if(!$last_bal){
							$last_bal = 0;
						}
						$last_bal -= $mall_point;
						@mysql_query("update $db->member_ewallet_record set bal='$last_bal' where id='$new_eid' limit 1");
					}
					
					
					if(!mysql_query($sql="update $db->users set mwallet=mwallet+$mall_point where id='$uid' limit 1")){
						$update_mw_err.="UID: $uid, amount: $mall_point\n";
					}elseif(!mysql_query($sql="insert into $db->member_mwallet_record (uid, type, amount, descr, cdate) values ('$uid', 'credit', '$mall_point', '".addslashes("Credited $vars[currency]".number_format($mall_point, 2)." for maintenance from bulk Pool commission received.")."', '".ndate()."')")){
						$insert_mwrec_err.=$sql."\n";
					}else{
						$new_eid = mysql_insert_id();
						$last_bal = @mysql_result(mysql_query("select bal from $db->member_mwallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
						if(!$last_bal){
							$last_bal = 0;
						}
						$last_bal += $mall_point;
						@mysql_query("update $db->member_mwallet_record set bal='$last_bal' where id='$new_eid' limit 1");
					}
				}
			}
		}
	}
	
	if($insert_error || $insert_poolcf_error || $insert_main_err){
		$status = false;
	}else{
		$status = true;
	}
	
	$errmsg = ($insert_error[1]? "Failed Pool 1 Calculations:<br />\n<br />\n$insert_error[1]" : "").
	($insert_error[2]? "Failed Pool 2 Calculations:<br />\n<br />\n$insert_error[2]" : "").
	($insert_error[3]? "Failed Pool 3 Calculations:<br />\n<br />\n$insert_error[3]" : "").
	($insert_poolcf_error? "Failed Pool Carry Forward Calculations:<br />\n<br />\n$insert_poolcf_error" : "").
	($insert_main_error? "Failed Maintenance Calculation:<br />\n<br />\n$insert_main_error" : "").
	($update_ew_err? "\nError crediting $vars[ewallet_title]:\n\n$update_ew_err" : "").
	($insert_ewrec_err? "\nError crediting $vars[ewallet_title] transactin record:\n\n$insert_ewrec_err" : "").
	($update_sw_err? "\nError crediting $vars[swallet_title]:\n\n$update_sw_err" : "").
	($insert_swrec_err? "\nError crediting $vars[swallet_title] transactin record:\n\n$insert_swrec_err" : "").
	($update_mw_err? "\nError crediting $vars[mwallet_title]:\n\n$update_mw_err" : "").
	($insert_mwrec_err? "\nError crediting $vars[mwallet_title] transactin record:\n\n$insert_mwrec_err" : "");
	
	return array('status'=>$status, 'errmsg'=>$errmsg);
}
?>